package cn.car.biz.impl;

import cn.car.biz.VehicleCommonInfoBiz;
import cn.car.domains.entity.VehicleCommonInfoEntity;
import cn.car.domains.vo.vehicleCommon.CreateVehicleCommonReq;
import cn.car.domains.vo.vehicleCommon.UpdateVehicleCommonReq;
import cn.car.domains.vo.vehicleCommon.VehicleCommonInfoRes;
import cn.car.exception.CarAccessControlException;
import cn.car.service.VehicleCommonInfoService;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

@Service
public class VehicleCommonInfoBizImpl implements VehicleCommonInfoBiz {

    // 注入服务层对象，委托数据操作逻辑
    @Resource
    private VehicleCommonInfoService vehicleCommonInfoService;

    /**
     * 创建车辆：VO转Entity + 调用服务层保存
     */
    @Override
    public void createVehicle(CreateVehicleCommonReq req) {
        // 1. 请求参数VO -> 数据库实体Entity
        VehicleCommonInfoEntity vehicleEntity = new VehicleCommonInfoEntity();
        BeanUtils.copyProperties(req, vehicleEntity);

        // 2. 补充VO未包含的默认值（若服务层未做自动填充）
        vehicleEntity.setEnabled(Boolean.TRUE); // 默认启用车辆

        // 3. 调用服务层保存，服务层已处理「车牌号重复」等业务异常
        vehicleCommonInfoService.insert(vehicleEntity);
    }

    /**
     * 按车牌号查车辆：服务层查Entity -> 转响应VO
     */
    @Override
    public VehicleCommonInfoRes getVehicleByNumber(String vehicleNumber) {
        // 1. 调用服务层按车牌号查询
        VehicleCommonInfoEntity vehicleEntity = vehicleCommonInfoService.getVehicleByNumber(vehicleNumber);
        if (vehicleEntity == null) {
            return null;
        }

        // 2. Entity -> VO
        VehicleCommonInfoRes vehicleRes = new VehicleCommonInfoRes();
        BeanUtils.copyProperties(vehicleEntity, vehicleRes);
        return vehicleRes;
    }

    /**
     * 更新车辆：先校验存在性 -> VO转Entity -> 调用服务层更新
     */
    @Override
    public void updateVehicle(UpdateVehicleCommonReq req) {
        // 1. 校验：车辆是否存在（避免更新不存在的数据）
        VehicleCommonInfoEntity existingVehicle = vehicleCommonInfoService.getVehicleById(req.getId());
        if (existingVehicle == null) {
            throw CarAccessControlException.DATE_NOT_EXIST.newInstance("车辆不存在，无法更新");
        }

        // 2. 更新请求VO -> 数据库实体Entity
        VehicleCommonInfoEntity updateEntity = new VehicleCommonInfoEntity();
        BeanUtils.copyProperties(req, updateEntity);

        // 3. 调用服务层执行更新
        vehicleCommonInfoService.updateVehicle(updateEntity);
    }

    /**
     * 删除车辆：先校验存在性 -> （可选）关联校验 -> 调用服务层删除
     */
    @Override
    public void deleteVehicle(Long id) {
        // 1. 校验：车辆是否存在
        VehicleCommonInfoEntity existingVehicle = vehicleCommonInfoService.getVehicleById(id);
        if (existingVehicle == null) {
            throw CarAccessControlException.DATE_NOT_EXIST.newInstance("车辆不存在，无法删除");
        }

        // 3. 调用服务层执行删除
        vehicleCommonInfoService.deleteVehicle(id);
    }



}
